﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PatientManagement.Database;
using PatientManagement.Managers;

namespace PatientManagement
{
    public partial class FormPrescription : Form
    {
        private int m_PrescriptionId;
        private bool m_EnabledEvent;
        public FormPrescription(int prescriptionId)
        {
            m_PrescriptionId = prescriptionId;
            m_EnabledEvent = false;
            InitializeComponent();
            dtgPrescription.AutoGenerateColumns = false;
            InitData();
        }

        public void InitData()
        {
            colDrug.DataSource = ServiceManager.Instance.GetAllGrugs();
            colDrug.DisplayMember = "Name";
            colDrug.ValueMember = "Id";
            GetPrescriptionDetails();
            m_EnabledEvent = true;
        }

        public void GetPrescriptionDetails()
        {
            var prescriptionDetails = ServiceManager.Instance.GetPrescriptionDetails(m_PrescriptionId);
            prescriptionDetails.ForEach(prescription =>
            {
                dtgPrescription.Rows.Add(prescription.Id, prescription.DrugId,
                    prescription.Usage, prescription.Amount, Convert.ToInt64(prescription.Price), 
                    Convert.ToInt64(prescription.Amount * prescription.Price), false);
            });

            CalcTotalOfMoney();
        }

        private void dtgPrescription_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (dtgPrescription.Columns["colDelete"].Index == e.ColumnIndex)
                {
                    var dialog = MessageBox.Show("Bạn có muốn xóa không ?", "Xác nhận", MessageBoxButtons.YesNo);
                    if (dialog == DialogResult.Yes)
                    {
                        var row = dtgPrescription.Rows[e.RowIndex];
                        int detailId = Convert.ToInt32(row.Cells["colId"].Value);
                        var result = ServiceManager.Instance.DeletePrescriptionDetails(detailId);
                        if (result)
                        {
                            dtgPrescription.Rows.RemoveAt(e.RowIndex);
                        }
                        else
                        {
                            MessageBox.Show("Xóa thất bại");
                        }
                    }
                }
            }
        }

        private void dtgPrescription_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is ComboBox)
            {
                var cbo = e.Control as ComboBox;

                cbo.DropDownStyle = ComboBoxStyle.DropDown;

                cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;

                cbo.AutoCompleteSource = AutoCompleteSource.ListItems;
            }

            if (dtgPrescription.CurrentCell.ColumnIndex == dtgPrescription.Columns["colAmount"].Index ||
                dtgPrescription.CurrentCell.ColumnIndex == dtgPrescription.Columns["colPrice"].Index
                )
            {
                TextBox item = e.Control as TextBox;
                if (item != null)
                {
                    item.KeyPress += new KeyPressEventHandler(item_KeyPress);
                }
            }
            else
            {
                TextBox allowText = e.Control as TextBox;
                if (allowText != null)
                {
                    allowText.KeyPress += new KeyPressEventHandler(allowText_KeyPress);
                }
            }
        }

        private void allowText_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = false;
        }

        private void item_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void dtgPrescription_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (m_EnabledEvent && e.RowIndex >= 0)
            {
                dtgPrescription["colValueChanged", e.RowIndex].Value = true;
                if (e.ColumnIndex == dtgPrescription.Columns["colAmount"].Index ||
                    e.ColumnIndex == dtgPrescription.Columns["colPrice"].Index)
                {
                    var price = dtgPrescription["colPrice", e.RowIndex].Value;
                    var amount = dtgPrescription["colAmount", e.RowIndex].Value;
                    if (price != null && amount != null)
                    {
                        dtgPrescription["colTotalPrice", e.RowIndex].Value = Convert.ToDecimal(price) * Convert.ToDecimal(amount);
                        CalcTotalOfMoney();
                    }
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            bool isError = false;
            for (int i = 0; i < dtgPrescription.Rows.Count - 1; i++)
            {
                bool rowError = false;
                var row = dtgPrescription.Rows[i];
                if (row.Cells["colDrug"].Value == null || row.Cells["colPrice"].Value == null || row.Cells["colAmount"].Value == null)
                {
                    rowError = true;
                    isError = true;
                }

                if (rowError)
                {
                    row.ErrorText = "Vui lòng nhập đầy đủ thông tin";
                    rowError = false;
                }
                else
                {
                    row.ErrorText = "";
                }
            }

            if (!isError)
            {
                for (int i = 0; i < dtgPrescription.Rows.Count - 1; i++)
                {
                    var row = dtgPrescription.Rows[i];
                    object isChanged = row.Cells["colValueChanged"].Value;
                    var detail = new PrescriptionDetail()
                    {
                        Id = Convert.ToInt32(row.Cells["colId"].Value),
                        DrugId = Convert.ToInt32(row.Cells["colDrug"].Value),
                        Amount = Convert.ToDecimal(row.Cells["colAmount"].Value),
                        Price = Convert.ToDecimal(row.Cells["colPrice"].Value),
                        PrescriptionId = m_PrescriptionId
                    };

                    if (isChanged != null)
                    {
                        if (Convert.ToBoolean(isChanged))
                        {
                            //Update
                            if (row.Cells["colId"].Value != null)
                            {
                                ServiceManager.Instance.UpdatePrescriptionDetails(detail);
                            }
                            else
                            {
                                //Add
                                ServiceManager.Instance.AddPrescriptionDetail(detail);
                            }
                        }
                    }
                }
                this.Close();
            }

        }

        private void CalcTotalOfMoney()
        {
            long total = 0;
            for (int i = 0; i < dtgPrescription.Rows.Count - 1; i++)
            {
                if (dtgPrescription["colTotalPrice", i].Value != null)
                {
                    total += Convert.ToInt64(dtgPrescription["colTotalPrice", i].Value);
                }
            }
            lbTotal.Text = total != 0 ? total.ToString("0,00.## đ") : string.Empty;
        }

    }
}
